import { appStore } from '@renderer/store/modules/app'
import { defineComponent, onUnmounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import _ from 'lodash'
import { Record } from '@renderer/types/game'
import { loadJsonStorage, saveJsonStorage } from '@renderer/utils/helper'
import { RECORD_STORAGE_KEY } from '@renderer/constants'
import { formatTime } from '@renderer/utils/time'
const { ipcRenderer } = require('electron')

const NULL_RECORDS: Record[] = [null, null, null, null]

export default defineComponent({
  name: 'RecordModal',
  setup () {
    const modalVisible = ref(false)
    const isLoadMode = ref(false)
    const currentIndex = ref(-1)
    const state: { records: Record[] } = reactive({
      records: []
    })
    const openDialog = (e, arg) => {
      const { isGameStart } = appStore
      if (!arg && !isGameStart) {
        message.error('只能在游戏中存档')
        return
      }
      state.records = loadJsonStorage(RECORD_STORAGE_KEY) || _.clone(NULL_RECORDS)
      currentIndex.value = -1
      isLoadMode.value = arg
      modalVisible.value = true
    }
    ipcRenderer.on('record', openDialog)

    const handleDialogOk = () => {
      const data = _.cloneDeep(state.records)
      const index = currentIndex.value
      if (isLoadMode.value) {
        const record = data[index]
        if (!record) {
          message.error('不能加载空记录')
          return
        }
        appStore.initGameFromLoad(record)
        modalVisible.value = false
      } else {
        const { gridData, gridSize, newBlockNum, power } = appStore
        data[index] = {
          time: new Date(),
          data: gridData,
          gridSize,
          newBlockNum,
          power
        }
        saveJsonStorage(RECORD_STORAGE_KEY, data)
        modalVisible.value = false
      }
    }

    onUnmounted(() => {
      ipcRenderer.removeAllListeners('record')
    })
    /* render 函数 */
    return () => {
      const records = state.records.map((record, index) => {
        const activeClass = index === currentIndex.value ? 'active' : ''
        const recordContent = record
          ? (
            <div class="flex-1 ml-2 text-center text-sm">
              <div>存档时间
                <span class="ml-4">{ formatTime(record.time) }</span>
              </div>
              <div class="flex justify-center">
                <div>游戏格数 {  record.gridSize }</div>
                <div class="ml-4">单次新增格数 {  record.newBlockNum }</div>
              </div>
            </div>
          )
          : (
            <div class="flex-1 ml-2 text-center">空</div>
          )
        return (
          <div
            class={`record-box ${activeClass} flex border-2 border-solid text-lg mt-2 rounded items-center cursor-pointer`}
            onClick={() => { currentIndex.value = index }}>
            <div class={`record-title rounded text-white p-2 box-border`}>存档 { index + 1 }</div>
            { recordContent}
          </div>
        )
      })
      return (
        <a-modal
          class="record-modal"
          title={`${isLoadMode.value ? '游戏读档' : '游戏存档'}`}
          v-model={[modalVisible.value, 'visible']}
          onOk={ handleDialogOk }>
          { records }
        </a-modal>
      )
    }
  }
})
